package com.dlc.shop.poly.common.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.linchuang.seneca.enums.PolyErrorCodeEnum;
import com.linchuang.seneca.enums.PolyMallRefundStatusEnum;
import com.linchuang.seneca.exception.PolyMallException;
import com.linchuang.seneca.request.*;
import com.linchuang.seneca.response.*;
import com.linchuang.seneca.utils.PolyMallResponseManage;
import com.dlc.shop.bean.dto.OrderRefundDto;
import com.dlc.shop.bean.dto.StockPointSkuDTO;
import com.dlc.shop.bean.dto.WarehouseDTO;
import com.dlc.shop.bean.enums.OrderActivityType;
import com.dlc.shop.bean.enums.StockBillType;
import com.dlc.shop.bean.enums.StockType;
import com.dlc.shop.bean.model.*;
import com.dlc.shop.bean.param.EsProductParam;
import com.dlc.shop.bean.param.OrderParam;
import com.dlc.shop.bean.vo.SkuStockVO;
import com.dlc.shop.bean.vo.WarehouseVO;
import com.dlc.shop.bean.vo.search.ProductSearchVO;
import com.dlc.shop.common.bean.UploadFile;
import com.dlc.shop.common.config.Constant;
import com.dlc.shop.common.constants.SegmentIdKey;
import com.dlc.shop.common.constants.StockPointType;
import com.dlc.shop.common.enums.StatusEnum;
import com.dlc.shop.common.util.DateUtils;
import com.dlc.shop.common.util.EsPageVO;
import com.dlc.shop.common.util.PageParam;
import com.dlc.shop.config.ShopConfig;
import com.dlc.shop.delivery.common.param.DeliveryOrderItemParam;
import com.dlc.shop.delivery.common.service.DeliveryOrderService;
import com.dlc.shop.poly.common.service.PolyMallOrderService;
import com.dlc.shop.search.common.constant.EsConstant;
import com.dlc.shop.search.common.param.EsPageParam;
import com.dlc.shop.search.common.service.SearchProductService;
import com.dlc.shop.service.*;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;


import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author: Seneca.vin
 * @date: 2023/9/12 16:54
 * @description: 菠萝派自建商城 order
 */
@Slf4j
@Service
@AllArgsConstructor
public class PolyMallOrderServiceImpl implements PolyMallOrderService {

    private final ShopConfig shopConfig;
    private final SearchProductService searchProductService;
    private final WarehouseService warehouseService;
    private final SkuService skuService;
    private final OrderService orderService;
    private final OrderItemService orderItemService;
    private final UserAddrOrderService userAddrOrderService;
    private final UserService userService;
    private final DeliveryOrderService deliveryOrderService;
    private final DeliveryService deliveryService;
    private final OrderRefundService orderRefundService;
    private final SegmentService segmentService;
    private final StockBillLogService stockBillLogService;

    @Override
    public PolyMallCommonResponse queryOrders(PolyMallCommonRequest request) throws PolyMallException {
        PolyMallOrderRequest orderRequest = JSONObject.parseObject(request.getBizcontent()).toJavaObject(PolyMallOrderRequest.class);
        orderRequest.checkRequest();
        //TODO 处理自己的分页和业务逻辑..
        //    ，，等待买家确认收货=JH_03，
        // * 交易成功=JH_04，交易关闭=JH_05，其他=JH_98（根据订单号查详情时）
        // * ，所有订单=JH_99)（目前会抓取JH_01,JH_02,JH_05三种状态的订单, 但ERP只会处理JH_02待发货的订单）
        //处理订单数据
        OrderParam orderParam = new OrderParam();
        PageParam<Order> page = new PageParam<>();
        String orderStatus = orderRequest.getOrderStatus();
        switch (orderStatus) {
            case "JH_01":
                //等待买家付款=JH_01
                //状态状态（1 没有付款.待付款）
                orderParam.setStatus(1);
                break;
            case "JH_02":
                // 等待卖家发货=JH_02
                //状态状态（2 已经付款,但卖家没有发货.待发货.）
                orderParam.setStatus(2);
                break;
            case "JH_03":
                // 交易成功=JH_03
                //状态状态（3 发货，导致实际库存减少，没有确认收货.待收货）
                orderParam.setStatus(3);
                break;
            case "JH_04":
                // 交易成功=JH_04
                //状态状态（5 订单确认收货成功，购买数增加1.）
                orderParam.setStatus(5);
                break;
            case "JH_05":
                // 交易关闭=JH_05
                //状态状态（6  交易失败.,还原库存）
                orderParam.setStatus(6);
                break;
            case "JH_99":
                // 所有订单=JH_99
                break;
        }
        page.setCurrent(orderRequest.getPageIndex());
        page.setSize(orderRequest.getPageSize());
        orderParam.setOrderNumber(orderRequest.getPlatOrderNo());
        String timeType = orderRequest.getTimeType();
        if (timeType != null) {
            switch (timeType) {
                case "JH_01":
                    //订单时间类别(订单修改时间=JH_01，订单创建时间=JH_02) (ERP抓单默认JH_02)
                    //状态状态（1 没有付款.待付款）
                    Date startTime = orderRequest.getStartTime();
                    Date endTime = orderRequest.getEndTime();
                    orderParam.setStartTime(startTime);
                    orderParam.setEndTime(endTime);
                    break;
                case "JH_02":
                    // 订单时间类别(订单修改时间=JH_01，订单创建时间=JH_02) (ERP抓单默认JH_02)
                    //状态状态（2 已经付款,但卖家没有发货.待发货）
                    Date startTime2 = orderRequest.getStartTime();
                    Date endTime2 = orderRequest.getEndTime();
                    orderParam.setStartTime(startTime2);
                    orderParam.setEndTime(endTime2);
                    break;
            }
        }
        IPage<Order> orderPage = orderService.pageOrdersDetailByOrderParam(page, orderParam);
        for (Order order : orderPage.getRecords()) {
            List<OrderItem> orderItems = orderItemService.getOrderItemsByOrderNumber(order.getOrderNumber(), true);
            order.setOrderItems(orderItems);
            UserAddrOrder userAddrOrder = userAddrOrderService.getById(order.getAddrOrderId());
            order.setUserAddrOrder(userAddrOrder);
        }
        // 组装返回的数据
        List<PolyMallOrder> orderList = new ArrayList<>();
        Long numtotalorder = Long.parseLong(orderPage.getTotal() + "");
        for (Order order : orderPage.getRecords()) {
            PolyMallOrder polyMallOrder = new PolyMallOrder();
            Integer status = order.getStatus();
            switch (status) {
                case 1:
                    //等待买家付款=JH_01
                    //状态状态（1 没有付款.待付款）
                    polyMallOrder.setTradeStatus("JH_01");
                    break;
                case 2:
                    // 等待卖家发货=JH_02
                    //状态状态（2 已经付款,但卖家没有发货.待发货）
                    polyMallOrder.setTradeStatus("JH_02");
                    break;
                case 3:
                    // 交易成功=JH_03
                    //状态状态（3 发货，导致实际库存减少，没有确认收货.待收货）
                    polyMallOrder.setTradeStatus("JH_03");
                    break;
                case 5:
                    // 交易成功=JH_04
                    //状态状态（5 订单确认收货成功，购买数增加1.）
                    polyMallOrder.setTradeStatus("JH_04");
                    break;
                case 6:
                    // 交易关闭=JH_05
                    //状态状态（6  交易失败.,还原库存）
                    polyMallOrder.setTradeStatus("JH_05");
                    break;
            }
            //订单号
            polyMallOrder.setPlatOrderNo(order.getOrderNumber());
            //订单说明
            polyMallOrder.setTradeStatusdescription(order.getRemarks());
            //交易时间
            polyMallOrder.setTradetime(order.getCreateTime());
            //国家二位简码或国家名称
            polyMallOrder.setCountry("CN");
            //城市
            UserAddrOrder userAddrOrder = order.getUserAddrOrder();
            polyMallOrder.setProvince(userAddrOrder.getProvince());
            polyMallOrder.setCity(userAddrOrder.getCity());
            polyMallOrder.setArea(userAddrOrder.getArea());
            polyMallOrder.setAddress(userAddrOrder.getAddr());
            polyMallOrder.setZip(userAddrOrder.getPostCode());
            polyMallOrder.setMobile(userAddrOrder.getMobile());
            polyMallOrder.setCustomerremark(order.getRemarks());
            polyMallOrder.setSellerremark(order.getShopRemarks());
            Integer dvyType = order.getDvyType();
            switch (dvyType) {
                case 1:
                    //1:快递 2:自提 3：无需快递 4:同城配送
                    //配送方式
                    //JH_ExpressSend=快递，JH_FetchSend=到店自提，JH_LocalSend=同城配送，JH_PlatSend=平台配送，JH_BusinessMen=商家配送
                    polyMallOrder.setSendtype("JH_ExpressSend");
                    break;
                case 2:
                    polyMallOrder.setSendtype("JH_FetchSend");
                    break;
                case 3:

                    break;
                case 4:
                    polyMallOrder.setSendtype("JH_LocalSend");
                    break;

            }

            //货款金额
            polyMallOrder.setGoodsfee(BigDecimal.valueOf(order.getTotal()).setScale(8, RoundingMode.HALF_UP));
            // 合计应收（针对卖家）
            polyMallOrder.setTotalmoney(BigDecimal.valueOf(order.getActualTotal()).setScale(8, RoundingMode.HALF_UP));
            //订单优惠金额（针对整个订单的优惠）  金额赋值参考
            polyMallOrder.setFavourablemoney(BigDecimal.valueOf(order.getReduceAmount()).setScale(8, RoundingMode.HALF_UP));
            //支付时间
            polyMallOrder.setPaytime(order.getPayTime());
            //收货人
            polyMallOrder.setReceivername(userAddrOrder.getReceiver());
            //昵称
            User user = userService.getById(userAddrOrder.getUserId());
            polyMallOrder.setNick(user.getNickName());
            Integer payType = order.getPayType();
            if (payType == null) {
                polyMallOrder.setPaytype("JH_Other");
            } else {
                switch (payType) {
                    case 1:
                        //微信支付=,
                        polyMallOrder.setPaytype("JH_WeiXin");
                        break;
                    case 2:
                        //支付宝=,
                        polyMallOrder.setPaytype("JH_Alipay");
                        break;
                }
            }

            polyMallOrder.setShouldpaytype("担保交易");
            List<OrderItem> orderItems = order.getOrderItems();
            List<PolyMallOrderProduct> goodinfos = polyMallOrder.getGoodinfos();
            for (OrderItem orderItem : orderItems) {
                PolyMallOrderProduct polyMallOrderProduct = new PolyMallOrderProduct();
                polyMallOrderProduct.setProductId(orderItem.getSkuId() + "");
                polyMallOrderProduct.setSuborderno(orderItem.getOrderItemId() + "");
                polyMallOrderProduct.setTradegoodsno(orderItem.getSkuId() + "");
                polyMallOrderProduct.setPlatgoodsid(orderItem.getShopId() + "");
                Sku skuAndName = skuService.getSkuAndName(orderItem.getSkuId());
                polyMallOrderProduct.setPlatskuid(skuAndName.getSkuId() + "");
                polyMallOrderProduct.setOutItemID(orderItem.getShopId() + "");
                polyMallOrderProduct.setOutSkuID(skuAndName.getPartyCode());

                polyMallOrderProduct.setTradegoodsname(orderItem.getProdName());
                polyMallOrderProduct.setTradegoodsspec(orderItem.getProperties());
                polyMallOrderProduct.setGoodscount(orderItem.getProdCount());
                polyMallOrderProduct.setPrice(BigDecimal.valueOf(orderItem.getActualTotal()).setScale(8, RoundingMode.HALF_UP));
                polyMallOrderProduct.setIsgift(orderItem.getIsGiveaway());

                goodinfos.add(polyMallOrderProduct);
                if (orderItem.getComboList() != null && orderItem.getComboList().size() > 0) {
                    for (OrderItem orderItemCombo : orderItem.getComboList()) {
                        PolyMallOrderProduct polyMallOrderProductCombo = new PolyMallOrderProduct();
                        polyMallOrderProductCombo.setProductId(orderItemCombo.getSkuId() + "");
                        polyMallOrderProductCombo.setSuborderno(orderItemCombo.getOrderItemId() + "");
                        polyMallOrderProductCombo.setTradegoodsno(orderItemCombo.getSkuId() + "");
                        polyMallOrderProductCombo.setPlatgoodsid(orderItemCombo.getShopId() + "");
                        Sku skuAndNameCombo = skuService.getSkuAndName(orderItemCombo.getSkuId());
                        polyMallOrderProductCombo.setPlatskuid(skuAndNameCombo.getSkuId() + "");
                        polyMallOrderProductCombo.setOutItemID(orderItemCombo.getShopId() + "");
                        polyMallOrderProductCombo.setOutSkuID(skuAndNameCombo.getPartyCode());

                        polyMallOrderProductCombo.setTradegoodsname(orderItemCombo.getProdName());
                        polyMallOrderProductCombo.setTradegoodsspec(orderItemCombo.getProperties());
                        polyMallOrderProductCombo.setGoodscount(orderItemCombo.getProdCount());
                        polyMallOrderProductCombo.setPrice(BigDecimal.valueOf(orderItemCombo.getActualTotal()).setScale(8, RoundingMode.HALF_UP));
                        polyMallOrderProductCombo.setIsgift(orderItemCombo.getIsGiveaway());
                        goodinfos.add(polyMallOrderProductCombo);
                    }
                }
                if (orderItem.getGiveawayList() != null && orderItem.getGiveawayList().size() > 0) {
                    for (OrderItem orderItemGiveaway : orderItem.getComboList()) {
                        PolyMallOrderProduct Giveaway = new PolyMallOrderProduct();
                        Giveaway.setProductId(orderItemGiveaway.getSkuId() + "");
                        Giveaway.setSuborderno(orderItemGiveaway.getOrderItemId() + "");
                        Giveaway.setTradegoodsno(orderItemGiveaway.getSkuId() + "");
                        Giveaway.setPlatgoodsid(orderItemGiveaway.getShopId() + "");
                        Sku skuAndNameGiveaway = skuService.getSkuAndName(orderItemGiveaway.getSkuId());
                        Giveaway.setPlatskuid(skuAndNameGiveaway.getSkuId() + "");
                        Giveaway.setOutItemID(orderItemGiveaway.getShopId() + "");
                        Giveaway.setOutSkuID(skuAndNameGiveaway.getPartyCode());

                        Giveaway.setTradegoodsname(orderItemGiveaway.getProdName());
                        Giveaway.setTradegoodsspec(orderItemGiveaway.getProperties());
                        Giveaway.setGoodscount(orderItemGiveaway.getProdCount());
                        Giveaway.setPrice(BigDecimal.valueOf(orderItemGiveaway.getActualTotal()).setScale(8, RoundingMode.HALF_UP));
                        Giveaway.setIsgift(orderItemGiveaway.getIsGiveaway());
                        goodinfos.add(Giveaway);
                    }
                }
            }
            polyMallOrder.setGoodinfos(goodinfos);
            orderList.add(polyMallOrder);
        }
        return PolyMallResponseManage.orderSuccess(orderList, numtotalorder);
    }

    @Override
    public PolyMallCommonResponse checkRefund(PolyMallCommonRequest request) throws PolyMallException {
        PolyMallRefundRequest refundRequest = JSONObject.parseObject(request.getBizcontent()).toJavaObject(PolyMallRefundRequest.class);
        refundRequest.checkRequest();
        String orderID = refundRequest.getOrderID();
        Order order = orderService.getOrderByOrderNumber(orderID);
        Integer isRefund = order.getIsRefund();
        Integer refundStatus = order.getRefundStatus();
        if (refundStatus == null && (isRefund == null || isRefund == 0 ) && order.getReturnMoneySts() == null) {
            //根据自己业务来，无退款就写死无退款
            log.info("无退款状态，不操作直接返回");
            return PolyMallResponseManage.noneRefund();
        }
        //申请退款 退款状态(没有退款=JH_07，
        // 买家已经申请退款等待卖家同意=JH_01，
        // 卖家已经同意退款等待买家退货=JH_02，
        // 买家已经退货等待卖家确认收货=JH_03，
        // 卖家拒绝退款=JH_04，
        // 退款关闭=JH_05，
        // 退款成功=JH_06，
        // JH_09=部分退款，
        // 其他=JH_99)
        //1:申请退款 2:退款成功 3:部分退款成功 4:退款失败
        //order.getRefundStatus() 1 申请退款 2退款成功 3部分退款成功 4退款失败 5退款关闭
        // order.getReturnMoneySts() 1.买家申请 2.卖家接受 3.买家发货 4.卖家收货 5.退款成功 6.买家撤回申请 7.商家拒绝 -1.退款关闭"
        if (order.getRefundStatus() == 1 || order.getReturnMoneySts() == 1) {
            List<PolyMallRefund> childrenrefundStatus = new ArrayList<>();
            List<OrderItem> orderItems = order.getOrderItems();
            for (OrderItem orderItem : orderItems) {
                if (orderItem.getRefundSn() != null) {
                    PolyMallRefund polyMallRefund = new PolyMallRefund();
                    polyMallRefund.setRefundno(orderItem.getRefundSn());
                    polyMallRefund.setRefundStatus(returnMoneyStsRefundStatus(orderItem.getReturnMoneySts(),"JH_01").get("code"));
                    polyMallRefund.setRefundStatusdescription(returnMoneyStsRefundStatus(orderItem.getReturnMoneySts(),"JH_01").get("desc"));
                    polyMallRefund.setProductName(orderItem.getProdName());
                    polyMallRefund.setSuborderno(orderItem.getOrderNumber());
                    childrenrefundStatus.add(polyMallRefund);
                }
            }

            return PolyMallResponseManage.refund(PolyMallRefundStatusEnum.JH_01.getCode(), PolyMallRefundStatusEnum.JH_01.getDesc(), childrenrefundStatus);
        }
        if (order.getRefundStatus() == 2 ) {
            List<PolyMallRefund> childrenrefundStatus = new ArrayList<>();
            List<OrderItem> orderItems = order.getOrderItems();
            for (OrderItem orderItem : orderItems) {
                if (orderItem.getRefundSn() != null) {
                    PolyMallRefund polyMallRefund = new PolyMallRefund();
                    polyMallRefund.setRefundno(orderItem.getRefundSn());
                    polyMallRefund.setRefundStatus(returnMoneyStsRefundStatus(orderItem.getReturnMoneySts(),"JH_06").get("code"));
                    polyMallRefund.setRefundStatusdescription(returnMoneyStsRefundStatus(orderItem.getReturnMoneySts(),"JH_06").get("desc"));
                    polyMallRefund.setProductName(orderItem.getProdName());
                    polyMallRefund.setSuborderno(orderItem.getOrderNumber());
                    childrenrefundStatus.add(polyMallRefund);
                }
            }

            return PolyMallResponseManage.refund(PolyMallRefundStatusEnum.JH_06.getCode(), PolyMallRefundStatusEnum.JH_06.getDesc(), childrenrefundStatus);
        }
        if (order.getRefundStatus() == 3 ) {
            List<PolyMallRefund> childrenrefundStatus = new ArrayList<>();
            List<OrderItem> orderItems = order.getOrderItems();
            for (OrderItem orderItem : orderItems) {
                if (orderItem.getRefundSn() != null) {
                    PolyMallRefund polyMallRefund = new PolyMallRefund();
                    polyMallRefund.setRefundno(orderItem.getRefundSn());
                    polyMallRefund.setRefundStatus(returnMoneyStsRefundStatus(orderItem.getReturnMoneySts(),"JH_09").get("code"));
                    polyMallRefund.setRefundStatusdescription(returnMoneyStsRefundStatus(orderItem.getReturnMoneySts(),"JH_09").get("desc"));
                    polyMallRefund.setProductName(orderItem.getProdName());
                    polyMallRefund.setSuborderno(orderItem.getOrderNumber());
                    childrenrefundStatus.add(polyMallRefund);
                }
            }

            return PolyMallResponseManage.refund(PolyMallRefundStatusEnum.JH_09.getCode(), PolyMallRefundStatusEnum.JH_09.getDesc(), childrenrefundStatus);
        }
        //2.卖家接受 3.买家发货 4.卖家收货 5.退款成功 6.买家撤回申请 7.商家拒绝 -1.退款关闭
        if (order.getReturnMoneySts() == 2) {
            List<PolyMallRefund> childrenrefundStatus = new ArrayList<>();
            List<OrderItem> orderItems = order.getOrderItems();
            for (OrderItem orderItem : orderItems) {
                if (orderItem.getRefundSn() != null) {
                    PolyMallRefund polyMallRefund = new PolyMallRefund();
                    polyMallRefund.setRefundno(orderItem.getRefundSn());
                    polyMallRefund.setRefundStatus(returnMoneyStsRefundStatus(orderItem.getReturnMoneySts(),"JH_02").get("code"));
                    polyMallRefund.setRefundStatusdescription(returnMoneyStsRefundStatus(orderItem.getReturnMoneySts(),"JH_02").get("desc"));

                    polyMallRefund.setProductName(orderItem.getProdName());
                    polyMallRefund.setSuborderno(orderItem.getOrderNumber());
                    childrenrefundStatus.add(polyMallRefund);
                }
            }
            return PolyMallResponseManage.refund(PolyMallRefundStatusEnum.JH_02.getCode(), PolyMallRefundStatusEnum.JH_02.getDesc(), childrenrefundStatus);
        }

        //2.卖家接受 3.买家发货 4.卖家收货 5.退款成功 6.买家撤回申请 7.商家拒绝 -1.退款关闭
        if (order.getReturnMoneySts() == 3) {
            List<PolyMallRefund> childrenrefundStatus = new ArrayList<>();
            List<OrderItem> orderItems = order.getOrderItems();
            for (OrderItem orderItem : orderItems) {
                if (orderItem.getRefundSn() != null) {
                    PolyMallRefund polyMallRefund = new PolyMallRefund();
                    polyMallRefund.setRefundno(orderItem.getRefundSn());
                    polyMallRefund.setRefundStatus(returnMoneyStsRefundStatus(orderItem.getReturnMoneySts(),"JH_03").get("code"));
                    polyMallRefund.setRefundStatusdescription(returnMoneyStsRefundStatus(orderItem.getReturnMoneySts(),"JH_03").get("desc"));

                    polyMallRefund.setProductName(orderItem.getProdName());
                    polyMallRefund.setSuborderno(orderItem.getOrderNumber());
                    childrenrefundStatus.add(polyMallRefund);
                }
            }
            return PolyMallResponseManage.refund(PolyMallRefundStatusEnum.JH_03.getCode(), PolyMallRefundStatusEnum.JH_03.getDesc(), childrenrefundStatus);
        }

        if (order.getReturnMoneySts() == 7) {
            List<PolyMallRefund> childrenrefundStatus = new ArrayList<>();
            List<OrderItem> orderItems = order.getOrderItems();
            for (OrderItem orderItem : orderItems) {
                if (orderItem.getRefundSn() != null) {
                    PolyMallRefund polyMallRefund = new PolyMallRefund();
                    polyMallRefund.setRefundno(orderItem.getRefundSn());
                    polyMallRefund.setRefundStatus(returnMoneyStsRefundStatus(orderItem.getReturnMoneySts(),"JH_04").get("code"));
                    polyMallRefund.setRefundStatusdescription(returnMoneyStsRefundStatus(orderItem.getReturnMoneySts(),"JH_04").get("desc"));

                    polyMallRefund.setProductName(orderItem.getProdName());
                    polyMallRefund.setSuborderno(orderItem.getOrderNumber());
                    childrenrefundStatus.add(polyMallRefund);
                }
            }
            return PolyMallResponseManage.refund(PolyMallRefundStatusEnum.JH_04.getCode(), PolyMallRefundStatusEnum.JH_04.getDesc(), childrenrefundStatus);
        }
        if (order.getReturnMoneySts() == -1) {
            List<PolyMallRefund> childrenrefundStatus = new ArrayList<>();
            List<OrderItem> orderItems = order.getOrderItems();
            for (OrderItem orderItem : orderItems) {
                if (orderItem.getRefundSn() != null) {
                    PolyMallRefund polyMallRefund = new PolyMallRefund();
                    polyMallRefund.setRefundno(orderItem.getRefundSn());
                    polyMallRefund.setRefundStatus(returnMoneyStsRefundStatus(orderItem.getReturnMoneySts(),"JH_05").get("code"));
                    polyMallRefund.setRefundStatusdescription(returnMoneyStsRefundStatus(orderItem.getReturnMoneySts(),"JH_05").get("desc"));
                    polyMallRefund.setProductName(orderItem.getProdName());
                    polyMallRefund.setSuborderno(orderItem.getOrderNumber());
                    childrenrefundStatus.add(polyMallRefund);
                }
            }
            return PolyMallResponseManage.refund(PolyMallRefundStatusEnum.JH_05.getCode(), PolyMallRefundStatusEnum.JH_05.getDesc(), childrenrefundStatus);
        }
        //根据自己业务来，无退款就写死无退款
        return PolyMallResponseManage.noneRefund();
    }


    //申请退款 退款状态(没有退款=JH_07，
    // 买家已经申请退款等待卖家同意=JH_01，
    // 卖家已经同意退款等待买家退货=JH_02，
    // 买家已经退货等待卖家确认收货=JH_03，
    // 卖家拒绝退款=JH_04，
    // 退款关闭=JH_05，
    // 退款成功=JH_06，
    // JH_09=部分退款，
    // 其他=JH_99)
// order.getReturnMoneySts() 1.买家申请 2.卖家接受 3.买家发货 4.卖家收货 5.退款成功 6.买家撤回申请 7.商家拒绝 -1.退款关闭"
    public HashMap<String, String> returnMoneyStsRefundStatus(Integer status,String jh){
        HashMap<String, String> map = new HashMap<>();
        if(status == null ){
            map.put("code",jh);
            map.put("desc",PolyMallRefundStatusEnum.valueOf(jh).getDesc());
            return map;
        }

        switch (status){
            case 1:
                map.put("code",PolyMallRefundStatusEnum.JH_01.getCode());
                map.put("desc",PolyMallRefundStatusEnum.JH_01.getDesc());
                break;
            case 2:
                map.put("code",PolyMallRefundStatusEnum.JH_02.getCode());
                map.put("desc",PolyMallRefundStatusEnum.JH_02.getDesc());
                break;
            case 3:
                map.put("code",PolyMallRefundStatusEnum.JH_03.getCode());
                map.put("desc",PolyMallRefundStatusEnum.JH_03.getDesc());
                break;
            case 5:
                map.put("code",PolyMallRefundStatusEnum.JH_06.getCode());
                map.put("desc",PolyMallRefundStatusEnum.JH_06.getDesc());
                break;
            case 7:
                map.put("code",PolyMallRefundStatusEnum.JH_04.getCode());
                map.put("desc",PolyMallRefundStatusEnum.JH_04.getDesc());
                break;
            case -1:
                map.put("code",PolyMallRefundStatusEnum.JH_05.getCode());
                map.put("desc",PolyMallRefundStatusEnum.JH_05.getDesc());
                break;
        }
        return map;
    }

    @Override
    public PolyMallCommonResponse send(PolyMallCommonRequest request) throws PolyMallException {
        PolyMallSendRequest sendRequest = JSONObject.parseObject(request.getBizcontent()).toJavaObject(PolyMallSendRequest.class);
        sendRequest.checkRequest();
        String platOrderNo = sendRequest.getPlatOrderNo();
        Order order = orderService.getOrderByOrderNumber(platOrderNo);
        if (order == null) {
            // 订单不存在
            // throw new YamiShopBindException("yami.order.no.exist");
            throw new PolyMallException(PolyErrorCodeEnum.ORDER_ERROR.getCode(), PolyErrorCodeEnum.ORDER_ERROR.getDesc());
        }
        //根据 是否拆单发货(拆单=1 ，不拆单=0)
        if (sendRequest.getIsSplit() == 1) {
            List<OrderItem> orderItems = new ArrayList<>();
            String[] subPlatOrderNo = sendRequest.getSubPlatOrderNo().split("\\|");
            for (String s : subPlatOrderNo) {
                String[] orderItemNo = s.split("\\:");

                List<OrderItem> orderItemsByOrderNumber = orderItemService.getOrderItemsByOrderNumber(platOrderNo, true);
                //存需要发货的数据
                for (OrderItem orderItem : orderItemsByOrderNumber) {
                    if (orderItem.getOrderItemId().equals(orderItemNo[0])) {
                        orderItems.add(orderItem);
                    }
                }
                orderItems = getOrderItem( order, orderItems);
                //发货
                saveDeliveriesInfo(platOrderNo, orderItems, order, sendRequest);
            }
        } else {
            //不拆单处理
            List<OrderItem> orderItemsByOrderNumber = orderItemService.getOrderItemsByOrderNumber(platOrderNo, true);
            //发货
            orderItemsByOrderNumber = getOrderItem( order, orderItemsByOrderNumber);
            saveDeliveriesInfo(platOrderNo, orderItemsByOrderNumber, order, sendRequest);
        }

        return PolyMallResponseManage.sendSuccess();
    }

    public List<OrderItem> getOrderItem(Order order, List<OrderItem> orderItems) throws PolyMallException {
        if (CollectionUtils.isEmpty(orderItems)) {
            // 订单不存在
           // throw new YamiShopBindException("yami.order.no.exist");
            throw new PolyMallException(PolyErrorCodeEnum.ORDER_ERROR.getCode(), PolyErrorCodeEnum.ORDER_ERROR.getDesc());
        }
        Map<Long, Integer> orderItemMap = null;
        if (Objects.nonNull(order.getRefundStatus())) {
            orderItemMap = orderService.getOrderItemMap(order.getOrderId());
        }
        // 获取组合map
        Map<Long, List<OrderItem>> comboMap = orderItems.stream().filter(item -> Objects.equals(item.getActivityType(), OrderActivityType.COMBO_PROD.value()))
                .collect(Collectors.groupingBy(OrderItem::getActivityId));
        //查询已发货数量
        for (OrderItem orderItem : orderItems) {
            //根据状态查询可发货数量
            orderItem.setChangeNum(orderItem.getStatus() == -1 ? orderItem.getProdCount() : orderItem.getStatus());
            orderItem.setProdCount(orderItem.getChangeNum());
            if (Objects.nonNull(orderItemMap) && Objects.nonNull(orderItemMap.get(orderItem.getOrderItemId()))) {
                orderItem.setReturnMoneySts(orderItemMap.get(orderItem.getOrderItemId()));
            } else if (Objects.nonNull(orderItemMap) && Objects.nonNull(orderItemMap.get(0L))) {
                orderItem.setReturnMoneySts(orderItemMap.get(0L));
            }
            // 退款修改赠品状态
            if (Objects.nonNull(orderItemMap) && Objects.equals(orderItem.getActivityType(), OrderActivityType.GIVEAWAY.value()) && orderItemMap.containsKey(orderItem.getActivityId())) {
                orderItem.setReturnMoneySts(orderItemMap.get(orderItem.getActivityId()));
            }
            if (comboMap.containsKey(orderItem.getOrderItemId())) {
                comboMap.get(orderItem.getOrderItemId()).forEach(orderItemVO -> orderItemVO.setReturnMoneySts(orderItem.getReturnMoneySts()));
            }
        }
        return orderItems;
    }

    public void saveDeliveriesInfo(String platOrderNo, List<OrderItem> orderItemsByOrderNumber, Order order, PolyMallSendRequest sendRequest) throws PolyMallException {
        DeliveryOrderItemParam deliveryOrderParam = new DeliveryOrderItemParam();
        deliveryOrderParam.setOrderNumber(platOrderNo);
        deliveryOrderParam.setAddrOrderId(order.getAddrOrderId());
        deliveryOrderParam.setSelectOrderItems(orderItemsByOrderNumber);
        deliveryOrderParam.setReceiverMobile(order.getReceiverMobile());
        deliveryOrderParam.setReceiverName(order.getReceiverName());
        List<Delivery> list = deliveryService.list(Wrappers.lambdaQuery(Delivery.class)
                .gt(Delivery::getStatus, StatusEnum.DELETE.value())
                .like(!ObjectUtils.isEmpty(sendRequest.getLogisticName()), Delivery::getDvyName, sendRequest.getLogisticName()));
        if (list.size() > 0) {
            deliveryOrderParam.setDeliveryType(1);
            deliveryOrderParam.setDvyId(list.get(0).getDvyId());
            deliveryOrderParam.setDvyFlowId(sendRequest.getLogisticno());
        } else {
            throw new PolyMallException(PolyErrorCodeEnum.EXPRESS_ERROR.getCode(), PolyErrorCodeEnum.EXPRESS_ERROR.getDesc());
        }
        deliveryOrderService.saveDeliveriesInfo(deliveryOrderParam, orderItemsByOrderNumber.get(0).getShopId());
    }

    @Override
    public PolyMallCommonResponse downloadProduct(PolyMallCommonRequest request) throws PolyMallException {
        PolyMallProductRequest sendRequest = JSONObject.parseObject(request.getBizcontent()).toJavaObject(PolyMallProductRequest.class);
        sendRequest.checkRequest();
        //处理商品下载业务
        String productId = sendRequest.getProductId();
        String productName = sendRequest.getProductName();
        Integer pageIndex = sendRequest.getPageIndex();
        Integer pageSize = sendRequest.getPageSize();
        String status = sendRequest.getStatus();
        EsPageParam pageParam = new EsPageParam();
        pageParam.setCurrent(pageIndex);
        pageParam.setSize(pageSize);
        EsProductParam productParam = new EsProductParam();
        //默认为中文
        productParam.setLang(0);
        if (!"".equals(productId)) {
            productParam.setProdId(Long.parseLong(productId));
        }
        productParam.setKeyword(productName);
        productParam.setFetchSource(EsConstant.PLATFORM_FETCH_SOURCE);
        switch (status) {
            case "JH_01":
                //查询已经上架的商品
                //状态状态（-1:删除、0:商家下架、1:上架、2:违规下架、3:平台审核）
                productParam.setStatus(1);
                break;
            case "JH_02":
                // 查询下架的商品
                //状态状态（-1:删除、0:商家下架、1:上架、2:违规下架、3:平台审核）
                productParam.setStatus(0);
                break;
            case "JH_99":
                // 查询所有的商品
                //状态状态（-1:删除、0:商家下架、1:上架、2:违规下架、3:平台审核）
                break;
        }

        EsPageVO<ProductSearchVO> searchPage = searchProductService.adminPage(pageParam, productParam);
        this.handleProdStock(searchPage);
        PolyMallProductResponse polyMall = new PolyMallProductResponse();
        int i = searchPage.getTotal().intValue();
        polyMall.setTotalcount(i);
        List<PolyMallProduct> list = new ArrayList<>();
        UploadFile config = shopConfig.getUploadFile();
        for (ProductSearchVO record : searchPage.getRecords()) {
            PolyMallProduct polyMallProduct = new PolyMallProduct();
            //商品id
            polyMallProduct.setPlatProductID(record.getProdId() + "");
            polyMallProduct.setName(record.getProdName());
            polyMallProduct.setOuterID(record.getProdId() + "-" + record.getShopId() + "");
            polyMallProduct.setPrice(BigDecimal.valueOf(record.getPrice()).setScale(8, RoundingMode.HALF_UP));
            polyMallProduct.setNum(record.getTotalStocks());
            polyMallProduct.setPictureurl(config.getEndPoint() +"/"+config.getBucketName()+"/"+ record.getPic());

            List<Long> whsecodeList = new ArrayList<>();
            //获取sku 数据
            List<Sku> skus = skuService.listSkuAndSkuStock(record.getProdId(), null);
            List<PolyMallProductGoods> goodsskus = new ArrayList<>();
            for (Sku sku : skus) {
                PolyMallProductGoods polyMallProductGoods = new PolyMallProductGoods();
                polyMallProductGoods.setSkuID(sku.getSkuId() + "");
                polyMallProductGoods.setSkuname(sku.getSkuName());
                polyMallProductGoods.setSkuprice(BigDecimal.valueOf(sku.getPrice()).setScale(8, RoundingMode.HALF_UP));
                if (sku.getStocks() == null) {
                    polyMallProductGoods.setSkuQuantity(0);
                } else {
                    polyMallProductGoods.setSkuQuantity(sku.getStocks());
                }

                polyMallProductGoods.setSkuproperty(sku.getProperties());
                polyMallProductGoods.setSkuOuterID(sku.getPartyCode());
                polyMallProductGoods.setSkupictureurl(config.getEndPoint() +"/"+config.getBucketName()+"/"+ sku.getPic());
                for (StockPointSkuDTO stockPointSkuDTO : sku.getStockPointList()) {
                    if (stockPointSkuDTO.getStockPointIds() != null) {
                        whsecodeList.addAll(stockPointSkuDTO.getStockPointIds());
                    }
                    if (stockPointSkuDTO.getStockPointId() != null && stockPointSkuDTO.getStockPointId() != 0) {
                        whsecodeList.add(stockPointSkuDTO.getStockPointId());
                    }
                }
                goodsskus.add(polyMallProductGoods);
            }
            polyMallProduct.setWhsecode(whsecodeList.stream().distinct().collect(Collectors.toList()).toString());
            polyMallProduct.setSkus(goodsskus);
            list.add(polyMallProduct);
        }
        polyMall.setGoodslist(list);
        return PolyMallResponseManage.downloadProductSuccess(polyMall.getTotalcount(), polyMall.getGoodslist());
    }

    @Override
    public PolyMallCommonResponse syncStock(PolyMallCommonRequest request) throws PolyMallException {
        //库存不处理

        PolyMallSyncStockRequest syncStockRequest = JSONObject.parseObject(request.getBizcontent()).toJavaObject(PolyMallSyncStockRequest.class);
        syncStockRequest.checkRequest();
        //查询商品 更改库存
        String platProductID = syncStockRequest.getPlatProductID();
        String skuID = syncStockRequest.getSkuID();
        String whseCode = syncStockRequest.getWhseCode();
        String outSkuID = syncStockRequest.getOutSkuID();
        String outerID = syncStockRequest.getOuterID().split("-")[1];
        Integer quantity = syncStockRequest.getQuantity();
        log.info("不同步 商品库存");
        if (true){
            return PolyMallResponseManage.syncStockSuccess(quantity);
        }

        //根据商品编号查询  sku 和商品库存
        // if (whseCode == null || whseCode.equals("")) {
        //     //如果没有传  仓库编号，需要将 仓库编号修改为 默认编号
        //     whseCode = "";
        // }
        PageParam pageDTO = new PageParam();
        pageDTO.setSize(1);
        pageDTO.setCurrent(10000);
        WarehouseDTO warehouseDTO = new WarehouseDTO();
        warehouseDTO.setSkuId(Long.parseLong(skuID));
        if (outerID != null && !"".equals(outerID)) {
            warehouseDTO.setShopId(Long.parseLong(outerID));
        }
        if (whseCode != null && !"".equals(whseCode)) {
            //如果没有传  仓库编号，需要将 仓库编号修改为 默认编号
            warehouseDTO.setWarehouseId(Long.parseLong(whseCode));
        }
        warehouseDTO.setSysType(1);
        IPage<WarehouseVO> warehousePage = warehouseService.page(pageDTO, warehouseDTO);
        if (warehousePage.getTotal() > 10000) {
            pageDTO.setSize(1);
            pageDTO.setCurrent(warehousePage.getTotal());
            warehousePage = warehouseService.page(pageDTO, warehouseDTO);
        }
        List<WarehouseVO> records = warehousePage.getRecords();
        // 根据网站商品库存进行修改 商品是入库还是出库
        Integer stock = 0;
        Integer warehouseType = 0;
        for (WarehouseVO record : records) {
            if (whseCode != null && !"".equals(whseCode)) {
                if (whseCode.equals(record.getWarehouseId())) {
                    stock += record.getStock();
                    outerID = record.getShopId() + "";
                    warehouseType = record.getType();
                }
            } else {
                stock += record.getStock();
                warehouseType = record.getType();
                outerID = record.getShopId() + "";
            }
            if (0 == record.getType()) {
                if (whseCode == null || "".equals(whseCode)) {
                    //如果没有传  仓库编号，需要将 仓库编号修改为 默认编号
                    whseCode = record.getWarehouseId() + "";
                    warehouseType = record.getType();
                }
            }
        }
        int stockwangzhan = 0;
        for (WarehouseVO record : records) {
            if (whseCode != null && !"".equals(whseCode)) {
                if (whseCode.equals(record.getWarehouseId())) {
                    stockwangzhan = record.getStock();
                }
            }
        }
        StockBillLog stockBillLog = new StockBillLog();
        //计算 数量
        if ((quantity - stock) == 0) {
            //直接返回
            log.info("erp与网站数量一致");
            return PolyMallResponseManage.syncStockSuccess(quantity);
        } else if ((quantity - stock) > 0) {
            // 大于 0 需要入库
            getStockBillLog(whseCode, skuID,
                    warehouseType, outerID, Math.abs(quantity - stock),
                    stockwangzhan, 7l, StockPointType.WAREHOUSE.getValue(), 1, 2);
        } else if ((quantity - stock) < 0) {
            // 小于0 需要出库
            getStockBillLog(whseCode, skuID,
                    warehouseType, outerID, Math.abs(quantity - stock),
                    stockwangzhan, 8l, StockPointType.WAREHOUSE.getValue(), 1, 1);
        }

        stockBillLogService.saveInfo(stockBillLog);

        return PolyMallResponseManage.syncStockSuccess(quantity);
    }

    public StockBillLog getStockBillLog(String whseCode, String skuID,
                                        Integer warehouseType, String outerID, Integer stockCount,
                                        Integer stockwangzhan, Long stockChangeReasonId, Integer stockPointType, Integer status, Integer type) {
        StockBillLog stockBillLog = new StockBillLog();
        stockBillLog.setBusinessTime(new Date());
        stockBillLog.setRemark("吉客云数据同步，入库或者出库");
        stockBillLog.setStatus(status);
        //吉客云数据 入库7 出库8
        stockBillLog.setStockChangeReasonId(stockChangeReasonId);
        stockBillLog.setStockPointId(Long.getLong(whseCode));
        stockBillLog.setStockPointType(stockPointType);
        //2入库，1 出库
        stockBillLog.setType(type);
        List<StockBillLogItem> stockBillLogItems = new ArrayList<>();
        //根据商品 编号和 sku 编号查询数据
        Sku sku = skuService.getSkuListBySkuId(Long.parseLong(skuID));

        StockBillLogItem stockBillLogItem = new StockBillLogItem();
        stockBillLogItem.setProdId(sku.getProdId());
        stockBillLogItem.setPic(sku.getPic());
        stockBillLogItem.setPartyCode(sku.getPartyCode());
        stockBillLogItem.setProdName(sku.getProdName());
        stockBillLogItem.setSkuId(sku.getSkuId());
        stockBillLogItem.setSkuName(sku.getSkuName());
        stockBillLogItem.setWarehouseType(warehouseType);
        stockBillLogItem.setStockCount(stockCount);
        stockBillLogItem.setStockPointId(Long.parseLong(whseCode));
        stockBillLogItem.setStockPointType(stockPointType);
        stockBillLogItem.setStockType(type);
        stockBillLogItem.setStocks(stockwangzhan);
        stockBillLogItems.add(stockBillLogItem);
        stockBillLog.setStockBillLogItems(stockBillLogItems);
        //出库操作下判断出库数是否超出库存数？执行出库 ： 返回错误消息
        stockBillLog.setShopId(Long.parseLong(outerID));
        //stockBillLog.setEmployeeId();
        //stockBillLog.setMakerMobile(shopEmployeeService.getShopEmployeeById(stockBillLog.getEmployeeId()).getMobile());
        if (Objects.equals(stockBillLog.getStockBillType(), StockBillType.PURCHASE_STORAGE.value())) {
            String purchaseNumber = Constant.PURCHASES_ORDER + segmentService.getDateFormatSegmentId(SegmentIdKey.PURCHASES_ORDER);
            stockBillLog.setSourceOrderNo(purchaseNumber);
        }
        if (!Objects.equals(stockBillLog.getStockBillType(), StockBillType.PURCHASE_STORAGE.value())) {
            stockBillLog.setStockBillType(Objects.equals(stockBillLog.getType(), StockType.OUT_OF_STOCK.value()) ? StockBillType.OTHER_OUTBOUND.value() : StockBillType.OTHER_STORAGE.value());
        }
        return stockBillLog;
    }

    @Override
    public PolyMallCommonResponse queryWareHouse(PolyMallCommonRequest request) throws PolyMallException {
        PolyMallQueryWareHouseRequest queryWareHouseRequest = JSONObject.parseObject(request.getBizcontent()).toJavaObject(PolyMallQueryWareHouseRequest.class);

        PageParam<WarehouseVO> pageParam = new PageParam<>();
        if (queryWareHouseRequest.getPageSize() != null) {
            pageParam.setSize(queryWareHouseRequest.getPageSize());
        }
        if (queryWareHouseRequest.getPageIndex() != null) {
            pageParam.setCurrent(queryWareHouseRequest.getPageIndex());
        }

        WarehouseDTO warehouseDTO = new WarehouseDTO();
        if (queryWareHouseRequest.getWareHouseCode() != null && !"".equals(queryWareHouseRequest.getWareHouseCode())) {
            warehouseDTO.setWarehouseId(Long.parseLong(queryWareHouseRequest.getWareHouseCode()));
        }
        IPage<WarehouseVO> page = warehouseService.page(pageParam, warehouseDTO);
        List<WarehouseVO> records = page.getRecords();
        ArrayList<PolyMallWareHouseInfo> objects = new ArrayList<>();
        for (WarehouseVO record : records) {
            PolyMallWareHouseInfo polyMallWareHouseInfo = new PolyMallWareHouseInfo();
            polyMallWareHouseInfo.setWareHouseCode(record.getWarehouseId() + "");
            polyMallWareHouseInfo.setWareHouseName(record.getWarehouseName());
            polyMallWareHouseInfo.setAliasName(record.getWarehouseName());
            polyMallWareHouseInfo.setWareHouseType(record.getType() + "");
            polyMallWareHouseInfo.setAddress(record.getAddress());
            polyMallWareHouseInfo.setAddressId(record.getProvinceId() + "-" + record.getCityId() + "" + record.getAreaId());
            polyMallWareHouseInfo.setContactPhone(record.getPhone());
            polyMallWareHouseInfo.setContactName(record.getManage());
            polyMallWareHouseInfo.setExtActive(record.getStockMode() + "");
            objects.add(polyMallWareHouseInfo);
        }

        return PolyMallResponseManage.queryWareHouseSuccess(page.getTotal(), objects);
    }


    @Override
    public PolyMallCommonResponse getRefund(PolyMallCommonRequest request) throws PolyMallException {
        //退货退款接口
        PolyMallGetRefundRequest getRefundRequest = JSONObject.parseObject(request.getBizcontent()).toJavaObject(PolyMallGetRefundRequest.class);
        getRefundRequest.checkRequest();
        PageParam<OrderRefundDto> page = new PageParam<>();
        page.setCurrent(getRefundRequest.getPageIndex());
        page.setSize(getRefundRequest.getPageSize());
        OrderRefundDto orderRefundDto = new OrderRefundDto();
        String startTime = DateUtils.dateToString(getRefundRequest.getBeginTime());
        String endTime = DateUtils.dateToString(getRefundRequest.getEndTime());
        IPage<OrderRefundDto> refundPage = orderRefundService.getPage(page, orderRefundDto, startTime, endTime, 1);
        long total = refundPage.getTotal();
        List<OrderRefundDto> records = refundPage.getRecords();
        //返回数据
        PolyMallGetRefundResponse polyMallGetRefundResponse = new PolyMallGetRefundResponse();
        polyMallGetRefundResponse.setTotalcount((int) total);
        polyMallGetRefundResponse.setIsSuccess(true);
        //退款订单 补充
        List<PolyMallRefundItem> refunds = polyMallGetRefundResponse.getRefunds();
        for (OrderRefundDto record : records) {
            // 创建
            PolyMallRefundItem polyMallRefundItem = new PolyMallRefundItem();

            polyMallRefundItem.setRefundno(record.getRefundSn());
            polyMallRefundItem.setPlatorderno(record.getOrderNumber());
            polyMallRefundItem.setTotalamount(BigDecimal.valueOf(record.getOrderAmount()).setScale(8, RoundingMode.HALF_UP));
            polyMallRefundItem.setPayamount(BigDecimal.valueOf(record.getPlatformRefundAmount()).setScale(8, RoundingMode.HALF_UP));
            User user = userService.getUserByUserId(record.getUserId());

            polyMallRefundItem.setBuyernick(user.getNickName());
            polyMallRefundItem.setSellernick(record.getShopName());
            polyMallRefundItem.setCreatetime(record.getApplyTime());
            polyMallRefundItem.setUpdatetime(record.getUpdateTime());
            polyMallRefundItem.setOrderstatus("JH_11");
            polyMallRefundItem.setOrderstatusdesc("退货订单");
            String refundStatus = record.getRefundStatus();
            switch (refundStatus) {
                //1 申请退款 2退款成功 3部分退款成功 4退款失败 -1退款关
                case "1":
                    polyMallRefundItem.setRefundstatus("JH_01");
                    polyMallRefundItem.setRefundstatusdesc("申请退款");
                    if (record.getRefundDelivery() != null) {
                        polyMallRefundItem.setRefundstatus("JH_03");
                        polyMallRefundItem.setRefundstatusdesc("已有物流信息，买家已经退货等待卖家确认收货");
                    }
                    break;
                case "2":
                    polyMallRefundItem.setRefundstatus("JH_06");
                    polyMallRefundItem.setRefundstatusdesc("退款成功");
                    break;
                case "3":
                    polyMallRefundItem.setRefundstatus("JH_99");
                    polyMallRefundItem.setRefundstatusdesc("部分退款成功");
                    break;
                case "4":
                    polyMallRefundItem.setRefundstatus("JH_04");
                    polyMallRefundItem.setRefundstatusdesc("退款失败");
                    break;
                case "-1":
                    polyMallRefundItem.setRefundstatus("JH_05");
                    polyMallRefundItem.setRefundstatusdesc("退款关闭");
                    break;
            }
            Boolean isReceiver = record.getIsReceiver();
            if (isReceiver != null) {
                if (isReceiver) {
                    polyMallRefundItem.setGoodsstatus("JH_02");
                    polyMallRefundItem.setGoodsStatusDesc("买家已收到货");
                } else {
                    polyMallRefundItem.setGoodsstatus("JH_01");
                    polyMallRefundItem.setGoodsStatusDesc("买家未收到货");
                }
            } else {
                polyMallRefundItem.setGoodsstatus("JH_98");
                polyMallRefundItem.setGoodsStatusDesc("数据库暂未记录到货状态信息");
            }
            if (record.getRefundDelivery() != null) {
                polyMallRefundItem.setGoodsstatus("JH_03");
                polyMallRefundItem.setGoodsStatusDesc("买家已退货,已有物流信息。");
            }
            Integer applyType = record.getApplyType();
            if (applyType == 1) {
                polyMallRefundItem.setHasgoodsreturn(false);
            } else if (applyType == 2) {
                polyMallRefundItem.setHasgoodsreturn(true);
            }
            polyMallRefundItem.setRefundAmount(record.getRefundAmount() + "");
            polyMallRefundItem.setReason(record.getBuyerReason());
            polyMallRefundItem.setDesc(record.getBuyerDesc());
            if (record.getRefundDelivery() != null) {
                RefundDelivery refundDelivery = record.getRefundDelivery();
                polyMallRefundItem.setLogisticname(refundDelivery.getDeyName());
                polyMallRefundItem.setLogisticno(refundDelivery.getDeyNu());
            }
            List<PolyMallRefundGoods> refundGoods = polyMallRefundItem.getRefundGoods();
            //循环订单内商品
            for (OrderItem orderItem : record.getOrderItems()) {
                PolyMallRefundGoods polyMallRefundGoods = new PolyMallRefundGoods();
                polyMallRefundGoods.setPlatProductId(orderItem.getSkuId() + "");
                Sku skuBySkuId = skuService.getSkuBySkuId(orderItem.getSkuId());
                polyMallRefundGoods.setOuterID(skuBySkuId.getPartyCode());
                polyMallRefundGoods.setSku(orderItem.getSkuName());
                polyMallRefundGoods.setRefundAmount(BigDecimal.valueOf(orderItem.getPrice()).setScale(8, RoundingMode.HALF_UP));
               // polyMallRefundGoods.setProductNum(orderItem.getChangeNum());
                polyMallRefundGoods.setSubTradeNo(orderItem.getOrderItemId() + "");
                polyMallRefundGoods.setReason(orderRefundDto.getBuyerReason());
                refundGoods.add(polyMallRefundGoods);
            }
            polyMallRefundItem.setRefundGoods(refundGoods);
            refunds.add(polyMallRefundItem);
        }
        return PolyMallResponseManage.GetRefund(polyMallGetRefundResponse, refunds);
    }

    private void handleProdStock(EsPageVO<ProductSearchVO> searchPage) {
        List<Long> prodIds = searchPage.getRecords().stream().map(ProductSearchVO::getProdId).toList();
        if (prodIds.size() == 0) {
            return;
        }
        Map<Long, SkuStockVO> prodStockMap = skuService.mapProdStock(prodIds);
        for (ProductSearchVO productSearchVO : searchPage.getRecords()) {
            SkuStockVO skuStockVO = prodStockMap.get(productSearchVO.getProdId());
            productSearchVO.setTotalStocks(skuStockVO.getStock());
        }
    }
}
